package co2.bean;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import org.hibernate.id.UUIDHexGenerator;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import co2.engine.Co2Constants;
import co2.engine.DAOInterface;
import co2.pojos.MstRole;
import co2.pojos.Silabus;

@ManagedBean
@ViewScoped
public class SilabusMasterBean extends AbstractBean implements Serializable {
	private static final long serialVersionUID = 1L;
	private Silabus material;
	
	@Autowired
	@Qualifier("daoI")
	private DAOInterface dao;
	
	private Silabus selObj;
	private List<MstRole> listRole;
	private String content;
	private UploadedFile uploadFile; 
	private final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS");
	private boolean svStatus;
	private boolean edStatus;
	
	
	@PostConstruct
	public void postCon(){
		material = new Silabus();
		listRole = dao.getAllRole();
		
		try{
			Map map = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
			
			if(map.get("idmat")!=null){
				String idmat = map.get("idmat").toString();
				material = (Silabus) dao.get(Silabus.class, idmat);
				svStatus=false;
				edStatus=true;
			}else{
				svStatus=true;
				edStatus=false;
				
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}

	public void save(){
		StringBuffer path = new StringBuffer();
		StringBuffer docroot = new StringBuffer();
		path.append(Co2Constants.UPLOAD_FILE_PATH).append(sdf.format(new Date()))
		.append(".")
		.append(uploadFile.getFileName().split("\\.")[1]);
		File file = new File(path.toString());
		docroot.append(Co2Constants.DOCROOT_PATH).append(file.getName());
		try{
			OutputStream out = new FileOutputStream(file);
			out.write(uploadFile.getContents());
			out.close();
			
			String id = (String) (new UUIDHexGenerator()).generate(null, null);
			material.setId(id);
			material.setImage(docroot.toString());
			dao.save(material);
//			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Data Saved", ""));
			String extUrl=FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath();

			FacesContext.getCurrentInstance().getExternalContext().redirect(extUrl+"/jsf/target/list_silabus.jsf");
			
		}catch(FileNotFoundException fnf){
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Upload Error "+path.toString()+" Not Found", ""));
		}catch(IOException io){
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Upload Failed: IOException", ""));
		}catch(Exception e){
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Error Saving", ""));
			e.printStackTrace();
		}finally{
			material = new Silabus();
		}
	}
	
	public void saveUpdate(){

		
		try{
			if(uploadFile!=null){
				StringBuffer path = new StringBuffer();
				StringBuffer docroot = new StringBuffer();
				path.append(Co2Constants.UPLOAD_FILE_PATH).append(sdf.format(new Date()))
				.append(".")
				.append(uploadFile.getFileName().split("\\.")[1]);
				File file = new File(path.toString());
				docroot.append(Co2Constants.DOCROOT_PATH).append(file.getName());
				
				OutputStream out = new FileOutputStream(file);
				out.write(uploadFile.getContents());
				out.close();
				material.setImage(docroot.toString());
			}
			dao.update(material);
			String extUrl=FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath();

			FacesContext.getCurrentInstance().getExternalContext().redirect(extUrl+"/jsf/target/list_silabus.jsf");
			
		}catch(FileNotFoundException fnf){
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Upload Error File Not Found", ""));
		}catch(IOException io){
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Upload Failed: IOException", ""));
		}catch(Exception e){
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Error Saving", ""));
			e.printStackTrace();
		}finally{
			material = new Silabus();
		}
	
	}
	
	public void handleFileUpload(FileUploadEvent event){
		FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
		StringBuffer path = new StringBuffer();
		path.append(Co2Constants.UPLOAD_FILE_PATH).append(event.getFile().getFileName());
		File file = new File(path.toString());
		try{
			OutputStream out = new FileOutputStream(file);
			out.write(event.getFile().getContents());
			out.close();
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Hore",""));
		}catch(FileNotFoundException fnf){
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Upload Error "+path.toString()+" Not Found", ""));
		}catch(IOException io){
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Upload Failed: IOException", ""));
		}
	}
	
	public List<MstRole> getListRole() {
		return listRole;
	}

	public void setListRole(List<MstRole> listRole) {
		this.listRole = listRole;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public UploadedFile getUploadFile() {
		return uploadFile;
	}

	public void setUploadFile(UploadedFile uploadFile) {
		this.uploadFile = uploadFile;
	}

	public boolean isSvStatus() {
		return svStatus;
	}

	public void setSvStatus(boolean svStatus) {
		this.svStatus = svStatus;
	}

	public boolean isEdStatus() {
		return edStatus;
	}

	public void setEdStatus(boolean edStatus) {
		this.edStatus = edStatus;
	}

	public DAOInterface getDao() {
		return dao;
	}

	public void setDao(DAOInterface dao) {
		this.dao = dao;
	}

	public Silabus getMaterial() {
		return material;
	}

	public void setMaterial(Silabus material) {
		this.material = material;
	}

	public Silabus getSelObj() {
		return selObj;
	}

	public void setSelObj(Silabus selObj) {
		this.selObj = selObj;
	}

	public SimpleDateFormat getSdf() {
		return sdf;
	}
}